#include "uimainwindow.h"
#include "ui_uimainwindow.h"

#include <QWidget>
#include <QMainWindow>
#include <QStatusBar>
#include <QApplication>
#include <QPushButton>
#include "loginwindow.h"
#include "netset.h"
#include "aboutdialog.h"
#include <QDialog>
#include <QColorDialog>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QErrorMessage>
#include <QInputDialog>
#include <QWizard>
#include <QWizardPage>
#include <QLabel>
#include <QProgressDialog>
#include <QTextStream>
#include <QDataStream>
#include <QDebug>
UIMainWindow::UIMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::UIMainWindow)
{
    ui->setupUi(this);
    ui->statusbar->showMessage("s_bar");
    //qApp 全局对象
    qApp->setStyleSheet("QPushButton#pushbutton { color: gray }\
                        QPushButton { color: red }");

                        //connect(ui->okButton,&QPushButton::clicked,ui->twoButton,&QPushButton::clicked);
                        //connect(ui->twoButton,&QPushButton::clicked,this,&UIMainWindow::close);

                        connect(ui->okButton,&QPushButton::clicked,this,&UIMainWindow::close);
            //    connect(ui->twoButton,&QPushButton::clicked,this,&UIMainWindow::close);
            initTableWidget();
    connect(ui->dbTab,&DBSetWindow::changeTableWindow,[=](){
        ui->tabWidget->setCurrentIndex(1);
    });
}

UIMainWindow::~UIMainWindow()
{
    delete ui;
}
//初始化tableWidget
void UIMainWindow::initTableWidget()
{
    QStringList sl;
    sl<<"姓名"<<"年龄"<<"性别";
    //设置列数
    ui->tableWidget->setColumnCount(sl.size());
    //设置表头
    ui->tableWidget->setHorizontalHeaderLabels(sl);

    //设置行数
    //    ui->tableWidget->setRowCount(10);
    //插入空行
    //    ui->tableWidget->insertRow(0);
    //    //设置数据
    //    ui->tableWidget->setItem(0,0,new QTableWidgetItem("bbl"));
    //    QSpinBox *sbox = new QSpinBox();
    //    sbox->setRange(0,100);
    //    ui->tableWidget->setCellWidget(0,1,sbox);
    //    QComboBox *cbox = new QComboBox();
    //    cbox->addItems(QStringList()<<"男"<<"女");
    //    ui->tableWidget->setCellWidget(0,2,cbox);
}
void UIMainWindow::handlerPerson(QString name, int age, QString gender)
{
    //    ui->textEdit->append(name);
    //    ui->textEdit->append(QString::number(age));
    //    ui->textEdit->append(gender);

    //获取当前表格的行数
    int curRow = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(curRow);
    ui->tableWidget->setItem(curRow,0,new QTableWidgetItem(name));
    ui->tableWidget->setItem(curRow,1,new QTableWidgetItem(QString::number(age)));
    ui->tableWidget->setItem(curRow,2,new QTableWidgetItem(gender));
}

void UIMainWindow::handlerPerson(Person p)
{
    qDebug()<<p.age<<","<<p.name<<","<<p.gender;
}

//不需要进行connect绑定
void UIMainWindow::on_loginAction_triggered()
{
    /*
     * 1、实例化窗口对象
     * 2、设置窗口被关闭时资源回收
     * 3、显示窗口
     */
    loginw = new LoginWindow;
    //设置窗口关闭的时候资源回收
    loginw->setAttribute(Qt::WA_DeleteOnClose);
    loginw->show();
}

void UIMainWindow::on_netSetAct_triggered()
{
    netSetWin = new NetSet;
    //设置窗口关闭的时候资源回收
    netSetWin->setAttribute(Qt::WA_DeleteOnClose);
    netSetWin->show();
}

void UIMainWindow::on_modalAct_triggered()
{
    //    QDialog *dlg= new QDialog(this);
    AboutDialog *dlg = new AboutDialog(this);
    dlg->open();  //窗口级模态
    //    dlg->exec();  //应用程序级模态
}

void UIMainWindow::on_modelessAct_triggered()
{
    QDialog *dlg = new QDialog;
    dlg->setAttribute(Qt::WA_DeleteOnClose);//
    dlg->show();
}

void UIMainWindow::on_colorAct_triggered()
{
    QColor co = QColorDialog::getColor(Qt::black,this,"color",QColorDialog::ShowAlphaChannel);
    ui->textEdit->setTextColor(co);
}

void UIMainWindow::on_openAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、调用open 打开文件
     * 3、调用read readAll readLine读文件
     * 4、处理读取的数据
     * 5、关闭文件
     */
    QString filename =  QFileDialog::getOpenFileName(this,"file1",".",
                                                     "all(*.*);;"
                                                     "Images (*.png *.xpm *.jpg);;"
                                                     "Text files (*.txt)");
    QFile file(filename);
    bool success = file.open(QIODevice::ReadOnly);
    if(!success)
    {
        QMessageBox::warning(this,"open","open failed",QMessageBox::Ok);
        return;
    }
    //读操作
    QByteArray text = file.readAll();
    file.close();

    ui->textEdit->append(text);
}


void UIMainWindow::on_errorAction_triggered()
{
    QErrorMessage* msg = QErrorMessage::qtHandler();
    msg->showMessage("hello");
    //需要手动调用show  exec显示对话框
    msg->show();
}

//自行补充  getFont()
void UIMainWindow::on_fontAction_triggered()
{
    bool ok;
    QFont font = QFontDialog::getFont(&ok, this);
    if (ok)
    {
        ui->textEdit->setFont(font);
    }
}

void UIMainWindow::on_msgAction_triggered()
{
    //    int ret = QMessageBox::critical(this,"错误","这是个错误对话框",
    //                          QMessageBox::Yes,
    //                          QMessageBox::No);

    int ret = QMessageBox::information(this,"info","information",
                                       QMessageBox::Yes|QMessageBox::No);
    if(ret == QMessageBox::Yes)
    {
        ui->textEdit->append("yes");
    }
    else if(ret == QMessageBox::No)
    {
        ui->textEdit->append("no");
    }
}

void UIMainWindow::on_inputAction_triggered()
{
    int res = QInputDialog::getInt(this,"inputInt","input int");
    //sprintf
    ui->textEdit->append(QString("int val:%1").arg(res));
}

void UIMainWindow::on_winzardAction_triggered()
{
    QWizard* win = new QWizard(this);
    QWizardPage *p1 =new QWizardPage;
    QLabel * lb1 =new QLabel("page1",p1);
    Q_UNUSED(lb1)
    QWizardPage *p2 =new QWizardPage;
    QLabel * lb2 =new QLabel("page2",p2);
    Q_UNUSED(lb2)
    win->addPage(p1);
    win->addPage(p2);

    win->show();
}

void UIMainWindow::on_progressAction_triggered()
{
    QProgressDialog *pdlg =new QProgressDialog(this);
    pdlg->setRange(0,100);
    pdlg->setValue(5);
    pdlg->show();
}

void UIMainWindow::on_saveAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、调用open 打开文件
     * 3、准备写入文件的数据
     * 4、调用write 写入文件
     * 5、关闭文件
     */
    QString filename =  QFileDialog::getOpenFileName(this,"file1",".",
                                                     "all(*.*);;"
                                                     "Images (*.png *.xpm *.jpg);;"
                                                     "Text files (*.txt)");
    QFile file(filename);
    bool success = file.open(QIODevice::WriteOnly);
    if(!success)
    {
        QMessageBox::warning(this,"open","open failed",QMessageBox::Ok);
        return;
    }
    //获取多行文本框的内容
    QString text = ui->textEdit->toPlainText();
    //写操作
    file.write(text.toUtf8());
    file.close();
}

void UIMainWindow::on_textReadAction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、关联QFile 实例化QTextStream 对象
     * 3、>> 读文件
     * 4、显示内容到文本框
     * 5、关闭文件
     */

    QFile file(QFileDialog::getOpenFileName(this));
    file.open(QIODevice::ReadOnly);
    QTextStream in(&file);

    QString text;
    while(!in.atEnd())
    {
        in>>text;
        ui->textEdit->append(text);
    }

    file.close();
}

void UIMainWindow::on_textWriteAction_triggered()
{
    QString filename =  QFileDialog::getOpenFileName(this,"file1",".",
                                                     "all(*.*);;"
                                                     "Images (*.png *.xpm *.jpg);;"
                                                     "Text files (*.txt)");
    QFile file(filename);
    bool success = file.open(QIODevice::WriteOnly);
    if(!success)
    {
        QMessageBox::warning(this,"open","open failed",QMessageBox::Ok);
        return;
    }

    QTextStream out(&file);
    QString textToWrite = ui->textEdit->toPlainText();
    out << textToWrite;

    file.close();
}

void UIMainWindow::on_dataWirteaction_triggered()
{
    /*
     * 1、实例化QFile对象
     * 2、关联QFile 实例化QDataStream 对象 打开文件
     * 3、<< 写文件
     * 5、关闭文件
     */
    QFile file(QFileDialog::getOpenFileName(this));
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);

    //获取文本框内容
    QString text = ui->textEdit->toPlainText();
    //拆分
    QStringList sl = text.split("\n");
    QString name = sl[0];
    int age =sl[1].toInt();
    QString gender = sl[2];
    //    qDebug()<<sl;
    out<<name<<age<<gender;
    file.close();
}

void UIMainWindow::on_dataReadaction_triggered()
{
    QString filename =  QFileDialog::getOpenFileName(this);
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QDataStream in(&file);

    QString name;
    int age;
    QString gender;
    in >> name >> age >> gender;

    file.close();

    ui->textEdit->append(QString("Name: %1, Age: %2, Score: %3").arg(name).arg(age).arg(gender));
}

void UIMainWindow::on_dataReadAction_triggered()
{
    QString filename =  QFileDialog::getOpenFileName(this);
    QFile file(filename);
    file.open(QIODevice::ReadOnly);
    QDataStream in(&file);

    QString name;
    int age;
    double score;
    in >> name >> age >> score;

    file.close();

    ui->textEdit->append(QString("Name: %1, Age: %2, Score: %3").arg(name).arg(age).arg(score));

}

void UIMainWindow::on_luruAction_triggered()
{
    /*
     * 1、实例化FormWindow 对象
     * 2、关闭窗口回收资源
     */
    FormWindow *fwin = new FormWindow;
    fwin->setAttribute(Qt::WA_DeleteOnClose);
    fwin->show();
    void (FormWindow::*psignal) (QString,int,QString) = &FormWindow::sendPerson;
    void (UIMainWindow::*pslot) (QString,int,QString) = &UIMainWindow::handlerPerson;
    connect(fwin,psignal,this,pslot);
    //    connect(fwin,
    //            static_cast<void(FormWindow::*)(Person)> (&FormWindow::sendPerson),
    //            this,
    //            static_cast<void(UIMainWindow::*)(Person)>(&UIMainWindow::handlerPerson));
}

void UIMainWindow::on_twoButton_clicked()
{
    disconnect(ui->okButton,&QPushButton::clicked,this,&UIMainWindow::close);
}



void UIMainWindow::on_removeAction_triggered()
{
    int curRow = ui->tableWidget->currentRow();
    ui->tableWidget->removeRow(curRow);
}

void UIMainWindow::on_comboBox_currentIndexChanged(const QString &arg1)
{
    QFile file(QString("://%1").arg(arg1));
    file.open(QIODevice::ReadOnly);
    this->setStyleSheet( file.readAll());
    file.close();
}

void UIMainWindow::on_dbAddAction_triggered()
{
    /*
     * 1、准备sql
     * 2、实例化QsqlQuery 对象
     * 3、执行sql  exec
     */

#if 0
    QString sql = "INSERT INTO stu (name,age,score) VALUES('bob',19,56);";

    QSqlQuery query;

    if(query.exec(sql))
    {
        QMessageBox::warning(this,"warn","插入数据成功",QMessageBox::Ok);
    }
    else
    {
        QMessageBox::warning(this,"warn","插入数据失败:"+query.lastError().text(),QMessageBox::Ok);
    }
#endif
}

void UIMainWindow::on_dbDelAction_triggered()
{
#if 0
    FormWindow *fw = new FormWindow;


    fw->setAttribute(Qt::WA_DeleteOnClose);
    fw->show();
    connect(fw,
            static_cast<void(FormWindow::*)(QString,int ,QString)>(&FormWindow::sendPerson),
            [&](QString name,int age ,QString gen){
        QString sql = QString ("delete from stu where name = '%1'").arg(name);
        QSqlQuery query(sql);

        if(query.exec())
        {
            QMessageBox::warning(this,"warn","删除数据成功",QMessageBox::Ok);
        }
        else
        {
            QMessageBox::warning(this,"warn","删除数据失败:"+query.lastError().text(),QMessageBox::Ok);
        }
    });
#else
    int curRow = ui->tableWidget->currentRow();
    qDebug() << "inter dekinfo:" << curRow;
    ui->tableWidget->setFocus();
    /*
    qDebug()<< ui->tableWidget->item(curRow,1)->text();
    QString sql = QString ("delete from stu where name = '%1'").arg(ui->tableWidget->item(curRow,1)->text());
    qDebug()<<sql;
    QSqlQuery query;

    if(query.exec(sql))
    {
        QMessageBox::warning(this,"warn","删除数据成功",QMessageBox::Ok);
    }
    else
    {
        QMessageBox::warning(this,"warn","删除数据失败:"+query.lastError().text(),QMessageBox::Ok);
    }
    ui->tableWidget->removeRow(curRow);
    */
#endif
}

void UIMainWindow::on_sqlQueryAction_triggered()
{
    QSqlQuery query("select * from stu");
    int rows = ui->tableWidget->rowCount();
    while(query.next())
    {
        ui->tableWidget->insertRow(rows);
        ui->tableWidget->setItem(rows,0, new QTableWidgetItem(query.value(0).toString()));
        ui->tableWidget->setItem(rows,1, new QTableWidgetItem(query.value(1).toString()));
        ui->tableWidget->setItem(rows,2, new QTableWidgetItem(query.value(2).toString()));
    }
//    ui->tabWidget->setCurrentIndex(1);
}

void UIMainWindow::on_MvdAction_triggered()
{
    MvdWindow * mvd =new MvdWindow;
    mvd->setAttribute(Qt::WA_DeleteOnClose);
    mvd->show();
}
